<!-- 添加商品 -->
<template>
   <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
            <!-- 顶部提示信息 -->
            <el-alert
                title="添加商品"
                type="info"
                show-icon
                center>
            </el-alert>
            <!-- 步骤条 -->
            <el-steps :space="200" :active="activeIndex" finish-status="success" align-center>
                <el-step title="基本信息" ></el-step>
                <el-step title="商品参数" ></el-step>
                <el-step title="商品属性" ></el-step>
                <el-step title="商品图片" ></el-step>
                <el-step title="商品内容" ></el-step>
                <el-step title="完成" ></el-step>
            </el-steps>
            <!-- 左侧tab -->
            <el-form 
                :model="basicInfoForm" 
                :rules="rules" 
                ref="addGoodsRef" 
                label-width="100px"
                label-position="top">
                <el-tabs 
                    tab-position="left" 
                    v-model="activeName"
                    @tab-click="handleClick"
                    :before-leave="beforeTabLeave">
                    <!-- 0 -->
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="basicInfoForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="basicInfoForm.goods_price"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="basicInfoForm.goods_weight"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="basicInfoForm.goods_number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader
                                v-model="basicInfoForm.goods_cat"
                                :options="cateList"
                                :props="{ 
                                    expandTrigger: 'hover',
                                    value: 'cat_id',
                                    label: 'cat_name',
                                    children: 'children'
                                }"
                                @change="handleChange">
                            </el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <!-- 1 -->
                    <el-tab-pane label="商品参数" name="1">
                        <el-form-item
                            v-for="item in paramList"
                            :key="item.id" 
                            :label="item.attr_name">
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox 
                                    v-for="(item1, index) in item.attr_vals"
                                    :key="index"
                                    :label="item1" border></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <!-- 2 -->
                    <el-tab-pane label="商品属性" name="2">
                        <el-form
                            v-for="item in attrList"
                            :key="item.id">
                            <el-form-item
                                :label="item.attr_name">
                                <el-input v-model="item.attr_vals"></el-input>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                    <!-- 3 -->
                    <el-tab-pane label="商品图片" name="3">
                        <el-form-item>
                            <el-upload
                                :action="uploadUrl"
                                :on-preview="handlePreview"
                                :on-remove="handleRemove"
                                :headers="uploadHeaders"
                                :on-success="handleSuccess"
                                list-type="picture">
                                <el-button type="primary" size="small" round>上传图片</el-button>
                            </el-upload>
                        </el-form-item>
                        <!--  -->
                        <el-dialog
                            title="图片预览"
                            :visible.sync="showPictureDialogVisible"
                            center
                            width="30%">
                            <img class="previewImg" :src="showPicPath" :title="showPicName">
                        </el-dialog>
                    </el-tab-pane>
                    <!-- 4 -->
                    <el-tab-pane label="商品内容" name="4">
                        <quill-editor class="qlEditor" v-model="basicInfoForm.goods_introduce"></quill-editor>
                        <el-button type="primary" @click="addGoods">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
   </div>
</template>

<script>
    import _ from 'lodash'
    export default {
        data () {
            return {
                // 当前步骤
                activeIndex: 0,
                // form 
                basicInfoForm: {
                    goods_name: 'negro',
                    goods_price: '18',
                    goods_weight: '18',
                    goods_number: '18',
                    goods_cat: [],
                    pics: [],
                    goods_introduce: 'negro',
                    attrs: []
                },
                // form 规则
                rules: {
                    goods_name: [
                        {
                            required: true,
                            message: '请输入商品名称',
                            trigger: 'blur'
                        }
                    ],
                    goods_price: [
                        {
                            required: true,
                            message: '请输入商品价格',
                            trigger: 'blur'
                        }
                    ],
                    goods_weight: [
                        {
                            required: true,
                            message: '请输入商品重量',
                            trigger: 'blur'
                        }
                    ],
                    goods_number: [
                        {
                            required: true,
                            message: '请输入商品数量',
                            trigger: 'blur'
                        }
                    ],
                    goods_cat: [
                        {
                            required: true,
                            message: '请输入商品分类',
                            trigger: 'blur'
                        }
                    ]
                },
                // 当前tab
                activeName: 0,
                // 商品分类列表
                cateList: [],
                // 动态参数列表
                paramList: [],
                // 静态属性列表
                attrList: [],
                // 上传地址
                uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
                // 上传图片时携带token
                uploadHeaders: {
                    Authorization: window.sessionStorage.getItem("token")
                },
                // 展示预览图片
                showPictureDialogVisible: false,
                // 预览图片的路径
                showPicPath: '',
                // 预览图片的名称
                showPicName: '',
            };
        },
        created() {
            this.getCateList()
            
        },
        methods: {
            // 切换tab时
            handleClick: async function() {
                // 切换tab时，步骤条随之变化
                this.activeIndex = +this.activeName
                // 获取动态参数列表
                if (this.activeIndex === 1 && this.paramList.length === 0) {
                    const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel: 'many'}})
                    if (res.meta.status !== 200) {
                        return this.$message.error('获取参数失败！')
                    }
                    // 将attr_vals变成array
                    res.data.forEach(item => {
                        if(item.attr_vals.length > 0){
                            item.attr_vals = item.attr_vals.split(" ")
                        }else{
                            item.attr_vals = []
                        }
                    })
                    this.paramList = res.data
                    console.log('paramList: ',this.paramList);
                }
                // 获取静态属性列表
                if (this.activeIndex === 2) {
                    console.log('2');
                    const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel: 'only'}})
                    if (res.meta.status !== 200) {
                        return this.$message.error('获取参数失败！')
                    }
                    this.attrList = res.data
                    console.log('attrList: ',this.attrList);
                }
            },
            // 阻止切换tab
            beforeTabLeave: function(activeName, oldActiveName) {
                if(oldActiveName === '0' && this.basicInfoForm.goods_cat.length !== 3) {
                    this.$message.warning('请先选择三级商品分类')
                    return false
                }
            },
            // 获取分类数据
            getCateList: async function() {
                const {data: res} = await this.$http.get('categories')
                if (res.meta.status !== 200){
                    return this.$message.error('获取商品分类列表失败')
                }
                this.cateList = res.data
            },
            // 只允许选择三级分类
            handleChange: function() {
                if(this.basicInfoForm.goods_cat.length !== 3) {
                    this.$message.warning('只能选择三级分类')
                    this.basicInfoForm.goods_cat = []
                    this.ParamList = []
                    this.attrList = []
                    this.isdisabled = true
                    return 
                }
            },
            // upload-点击图片名称时预览图片
            handlePreview: function(res) {
                console.log('预览图片: ', res);
                this.showPicPath = res.response.data.url
                this.showPicName = res.name
                this.showPictureDialogVisible = true
            },
            // 删除上传的图片
            handleRemove: function(res) {
                // console.log('删除图片: ',res.response.data.tmp_path);
                // 遍历找到图片路径
                for (var item of this.basicInfoForm.pics){
                    if (item.pic === res.response.data.tmp_path) {
                        // 找到要删的图片所在的数组的下标
                        const indexOfRmPic = this.basicInfoForm.pics.indexOf(item)
                        // 删除图片
                        this.basicInfoForm.pics.splice(indexOfRmPic, 1)
                        // console.log('basicInfoForm.pics: ', this.basicInfoForm.pics);
                    }
                }

            },
            // 上传成功
            handleSuccess: function(res) {
                const picObj = {
                    pic: res.data.tmp_path
                }
                this.basicInfoForm.pics.push(picObj)
                console.log('basicInfoForm: ', this.basicInfoForm);
            },
            // 确认添加商品
            addGoods: function() {
                const form = _.cloneDeep(this.basicInfoForm)
                form.goods_cat = form.goods_cat.join(',')
                if(!this.paramList.length) return this.$message.error('请选择商品参数')
                // 商品的动态参数
                this.paramList.forEach(item => {
                    const paramObj = {
                        attr_id: item.attr_id,
                        attr_value: item.attr_vals.join(',')
                    }
                    form.attrs.push(paramObj)
                })
                if(!this.attrList.length) return this.$message.error('请选择商品属性')
                this.attrList.forEach(item => {
                    const paramObj = {
                        attr_id: item.attr_id,
                        attr_value: item.attr_vals
                    }
                    form.attrs.push(paramObj)
                })
                console.log('paramList: ', this.paramList);
                console.log('attrList: ', this.attrList);
                this.$refs.addGoodsRef.validate(async valid => {
                    if(!valid) {
                        return this.$message.error('请填写完整信息！')
                    }
                    const {data: res} = await this.$http.post('goods',form)
                    console.log('添加商品的返回信息: ', res);
                    if (res.meta.status !== 201) {
                        return this.$message.error('添加商品失败')
                    }
                    this.$router.push('/goods')
                    this.$message.success('添加商品成功')
                })
                console.log('商品信息: ',form);
            }
        },
        computed: {
            // 当前选中的三级分类的id
            cateId() {
                if(this.basicInfoForm.goods_cat.length === 3){
                    return this.basicInfoForm.goods_cat[2]
                }
                return null
            }
        }
    }

</script>
<style lang='less' scoped>
.el-tabs {
    margin-left: 25px;
}
.el-tab-pane {
    margin-left: 50px;
}

.el-input {
    width: 700px;
}

.cateParams {
    font-size: 13px;
}

.el-checkbox {
    margin: 0 10px 0 0 !important
}

.previewImg {
    width: 100%;
}

.qlEditor {
    
    width: 90%;
}

</style>